<template>
  <div>
    <!-- <div class=" pb-4">
        <div class="  bg-blue-500 ">
          <div class="login  bg-white  ">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="demo-registerForm"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              maxlength="11"
              auto-complete="off"
              placeholder="用户名"
            >
              <i slot="prefix" class="login-icon el-input__icon el-icon-user-solid" style="font-size: 1.6rem"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
              maxlength="20"
              type="password"
              auto-complete="off"
              placeholder="密码由6~20个英文字母、符号或数字组合"
            >
              <i slot="prefix" class="login-icon el-input__icon el-icon-lock" style="font-size: 1.6rem;"></i>
            </el-input>
          </el-form-item>

          <el-form-item prop="code" class="code-input">
            <el-input
              v-model="loginForm.code"
              onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
            >
              <i slot="prefix" class="login-icon el-input__icon el-icon-s-claim" style="font-size: 1.6rem;"></i>
            </el-input>
            <div class="verify-btn-container">
              <img :src="codeUrl" style="height: 48px" @click="getCodeNum" class="login-code-img" />
            </div>
          </el-form-item>
          <div class="flex justify-between">
            <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
            <router-link :to="{ path: '/forgetPassword' }">
              <div style="height: 20px;color: #1678ff;text-align: right; margin-bottom: 32px">忘记密码?</div>
            </router-link>
          </div>

          <el-form-item style="width:100%;">
            <el-button
              :loading="loginLoading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click="handleLogin"
            >
              <span>登 录</span>
            </el-button>
          </el-form-item>
        </el-form>
          </div>
        </div>

    </div> -->

    <div class="register-container">
      <div class="bg-img">
        <el-image :src="bgImg" fit="cover" lazy></el-image>
      </div>
      <div class="logo-container">
        <router-link :to="{ path: '/index' }">
          <div class="logo-img">
            <el-image fit="contain" :src="websiteIcon"></el-image>
          </div>
        </router-link>
        <el-divider direction="vertical"></el-divider>
        <span class="sub-title">欢迎来到 瞪羚独角兽企业申报</span>
      </div>
      <div class="form-container">
        <div class="float-left-img">
          <el-image :src="leftImg" fit="fill"></el-image>
        </div>
        <div class="form-box">
          <div class="form-title text-left">
            <span :class="['active']">登录</span>

            <el-divider direction="vertical"></el-divider>

            <router-link :to="{ path: '/register' }">
              <span>注册</span>
            </router-link>
          </div>
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="demo-registerForm"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                maxlength="11"
                auto-complete="off"
                placeholder="手机号"
              >
                <i
                  slot="prefix"
                  class="login-icon el-input__icon el-icon-user-solid"
                  style="font-size: 1.6rem"
                ></i>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
                maxlength="20"
                type="password"
                auto-complete="off"
                placeholder="密码由6~20个英文字母、符号或数字组合"
                @keyup.enter.native="handleLogin"
              >
                <i
                  slot="prefix"
                  class="login-icon el-input__icon el-icon-lock"
                  style="font-size: 1.6rem"
                ></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="code" class="code-input">
              <el-input
                v-model="loginForm.code"
                onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="handleLogin"
              >
                <i
                  slot="prefix"
                  class="login-icon el-input__icon el-icon-s-claim"
                  style="font-size: 1.6rem"
                ></i>
              </el-input>
              <div class="verify-btn-container">
                <img
                  :src="codeUrl"
                  style="height: 48px"
                  @click="getCodeNum"
                  class="login-code-img"
                />
              </div>
            </el-form-item>
            <div class="flex justify-between">
              <el-checkbox
                v-model="loginForm.rememberMe"
                style="margin: 0px 0px 25px 0px"
                >记住密码</el-checkbox
              >
              <router-link :to="{ path: '/forgetPassword' }">
                <div
                  style="
                    height: 20px;
                    color: #1678ff;
                    text-align: right;
                    margin-bottom: 32px;
                  "
                >
                  忘记密码?
                </div>
              </router-link>
            </div>

            <el-form-item style="width: 100%">
              <el-button
                :loading="loginLoading"
                size="medium"
                type="primary"
                style="width: 100%"
                @click="handleLogin"
              >
                <span>登 录</span>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import Verify from "@/components/Verifition/Verify";

import { getBanner } from "@/api/banner";
import { getNoticeList } from "@/api/notice";
import { getPolicyList } from "@/api/policy";
import { getEnterpriseList } from "@/api/startEnterprise";
import { getCodeImg } from "@/api/login";

import { getToken } from "@/utils/auth";
import { getDeclareList } from "@/api/declareList";
import { addDeclare } from "@/api/declareList";

import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
  components: { Verify },
  name: "Login",
  computed: {
    ...mapGetters({
      token: "token",
      userName: "name",
    }),
    activeTableShow() {
      return (tabIndex) => {
        if (tabIndex == this.switchTab) {
          return true;
        } else {
          return false;
        }
      };
    },
    activeHeadClass() {
      return (itemId) => {
        if (this.activeHeadIndex == itemId) {
          return "active-notice-head";
        }
        return "";
      };
    },
    declareStatusObj(endTime) {
      return (endTime) => {
        let isCanDeclare = this.isOverNow(endTime);
        if (isCanDeclare) {
          return { text: "进行申报", color: "text-blue-500" };
        } else {
          return { text: "", color: "" };
        }
      };
    },
    declareTimeText() {
      return (endTime) => {
        return this.isOverNow(endTime);
      };
    },
  },

  data() {
    return {
      websiteIcon: require("@/assets/images/home/icon.png"),
      switchTab: 0,
      dialogLogin: false,
      activeBannerIndex: 0,
      bgImg: require("@/assets/images/login-bg.png"),
      leftImg: require("@/assets/images/login-left.png"),
      bannerList: [
        {
          picture: require("@/assets/images/img-placeholder.jpg"),
          redirectUrl: "",
          id: 3,
        },
      ],
      headList: [
        { id: 0, name: "通知公告" },
        { id: 1, name: "政策文件" },
      ],
      activeHeadIndex: 0,
      bussinessActiveIndex: "0",

      // 通知公告
      noticeList: [
        // {
        //   annunciatePolicyId: "",
        //   publishTime: "",
        //   title: ""
        // }
      ],
      // 政策列表
      policyList: [
        // {
        //   annunciatePolicyId: "",
        //   publishTime: "",
        //   title: ""
        // }
      ],

      // 明星企业
      imgList: [
        // {
        //   enterpriseId: 0,
        //   picture: "https://w.wallhaven.cc/full/e7/wallhaven-e76ge8.jpg"
        // },
        // {
        //   enterpriseId: 1,
        //   imgSrc: "https://w.wallhaven.cc/full/y8/wallhaven-y8267k.png"
        // },
        // {
        //   enterpriseId: 2,
        //   imgSrc: "https://w.wallhaven.cc/full/q2/wallhaven-q2mkzr.jpg"
        // },
        // {
        //   enterpriseId: 3,
        //   imgSrc: "https://w.wallhaven.cc/full/wq/wallhaven-wqdglr.jpg"
        // }
      ],
      declareTypeList: [
        {
          id: 0,
          dictLabel: "2021江西省瞪羚企业认定申报",
          dictValue: "0",
          startTime: "2020.12.31",
          endTime: "2021.12.31",
        },
        {
          id: 1,
          dictLabel: "2021江西省潜在瞪羚企业认定申报",
          dictValue: "1",
          startTime: "2020.12.31",
          endTime: "2020.12.31",
        },

        {
          id: 2,
          dictLabel: "2021江西省独角兽企业认定申报",
          dictValue: "2",
          startTime: "2020.12.31",
          endTime: "2021.12.31",
        },
        {
          id: 3,
          dictLabel: "2021江西省潜在独角兽企业认定申报",
          dictValue: "3",
          startTime: "2020.12.31",
          endTime: "2021.12.31",
        },
        {
          id: 4,

          dictLabel: "2021江西省种子独角兽企业认定申报",
          dictValue: "4",
          startTime: "2020.12.31",
          endTime: "2021.12.31",
        },
      ],

      // 申报列表
      declareList: [],

      classicDeclare: [
        {
          id: 0,
          name: "2021年度江西省瞪羚企业认定申报",
          startTime: "2020.11.20",
          endTime: "2021.10.19",
        },
      ],
      // 申报中的文件
      canDeclareList: [],
      allDeclare: [
        {
          id: 0,
          name: "2021年度江西省瞪羚企业认定申报",
          startTime: "2020.11.20",
          endTime: "2021.10.21",
        },
        {
          id: 1,
          name: "2021年度江西省瞪羚企业认定申报",
          startTime: "2020.11.20",
          endTime: "2021.10.22",
        },
        {
          id: 2,
          name: "2021年度江西省瞪羚企业认定申报",
          startTime: "2020.11.20",
          endTime: "2021.11.23",
        },
      ],
      declareStatus: [
        {
          id: 0,
          name: "已过期",
        },
        {
          id: 1,
          name: "待定",
        },
        {
          id: 2,
          name: "申报中",
        },
      ],
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        uuid: "",
        code: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "手机号不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
      },
      loginLoading: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
        if (route.query.isShowLogin) {
          this.dialogLogin = true;
        }
      },
      immediate: true,
    },
    dialogLogin(v) {
      let ishasshowLogin = this.$route.query.isShowLogin;
      if (ishasshowLogin && !v) {
        this.$router.push({
          path: "/login",
        });
      }
    },
  },
  created() {
    this.getCookie();
    if (this.token) {
      this.GetInfo();
    } else {
      this.getCodeNum();
    }
    this.initDeclareList();
    this.initBannerList();
    this.inintStartList();
    this.initNoticeList();
    this.initPolicyList();

    window.isCloseHint = true;

    window.addEventListener("beforeunload", function (e) {
      if (window.isCloseHint) {
        var confirmationMessage = ("注意保存所填写信息"(
          e || window.event
        ).returnValue = confirmationMessage);
        return confirmationMessage;
      }
    });
  },

  methods: {
    ...mapActions({
      LogOut: "LogOut", // 第一个blogAdd是定义的一个函数别名称，挂载在到this(vue)实例上，后面一个blogAdd 才是actions里面函数方法名称
      GetInfo: "GetInfo",
    }),
    signIn() {
      this.dialogLogin = true;
      this.getCookie();
      if (this.token) {
        this.GetInfo();
      } else {
        this.getCodeNum();
      }
    },
    signOut() {
      this.LogOut();
    },
    getTokenFun() {
      return getToken();
    },
    // 传入时间，检测时间是否超过今天
    isOverNow(time) {
      let endTime = JSON.parse(JSON.stringify(time));
      if (endTime) {
        let lineDateStr = endTime.replace(/\./g, "/");
        let date = new Date(lineDateStr);
        let nowTime = new Date();
        let nowTimeChuo = nowTime.valueOf();
        let endTimeChuo = date.valueOf();
        if (nowTimeChuo >= endTimeChuo) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    },

    getCodeNum() {
      getCodeImg().then((res) => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },

    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },

    capctchaCheckSuccess(params) {
      this.loginForm.code = params.captchaVerification;
      this.loginLoading = true;
      if (this.loginForm.rememberMe) {
        Cookies.set("username", this.loginForm.username, { expires: 30 });
        Cookies.set("password", encrypt(this.loginForm.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", this.loginForm.rememberMe, { expires: 30 });
      } else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      this.$store
        .dispatch("Login", this.loginForm)
        .then((res) => {
          this.$router.push({ path: this.redirect || "/" }).catch(() => {});
        })
        .catch((e) => {
          // this.msgError(e);
          this.loginLoading = false;
        });
    },

    handleLogin() {
      if (getToken()) {
        this.$router.push({ path: "/user" });
        return;
      }

      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loginLoading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router
                .push({ path: this.redirect || "/user" })
                .catch(() => {});
              // this.$router
              //   .push({ path: "/user" })
              //   .catch(() => { });
            })
            .catch((e) => {
              // this.msgError(e);
              this.loginLoading = false;
              this.getCodeNum();
            });
        }
      });
    },

    tableToDeclare(item) {},
    // handleLogin() {
    //   this.$refs.loginForm.validate(valid => {
    //     if (valid) {
    //       this.$refs.verify.show();
    //     }
    //   });
    // },

    toRegister() {
      this.$router.push({ path: "/register" });
    },
    adddeclareContent(typeId) {
      let requestObj = {
        year: 2021,
        type: typeId,
        status: 0,
      };
      addDeclare(requestObj).then((res) => {
        if (res.code == 200) {
        }
      });
    },
    toDeclareDetail(item) {
      let id = item.id;
      if (getToken()) {
        let requestObj = {
          year: 2021,
          type: id,
          status: 0,
          declareTime: item.startTime + "-" + item.endTime,
        };
        addDeclare(requestObj).then((res) => {
          if (res.code == 200) {
            let relationId = res.data.keyId;
            this.$router.push({
              path: "/enterprise/form",
              query: { id: relationId, typeId: id, declareIndex: 0 },
            });
          }
        });
      } else {
        // this.$message({
        //   type: "error",
        //   message: "您还未登录!"
        // });
        this.dialogLogin = true;
        this.LogOut();
        // this.token = false;
      }
    },
    setBannerImg(index) {
      this.$refs["headBanner"].setActiveItem(index);
      // this.activeBannerIndex = index
    },
    // 轮播图 handler change
    bannerImgChange(e) {
      this.activeBannerIndex = e;
    },
    // 初始化轮播
    initBannerList() {
      getBanner().then((res) => {
        if (res.code == 200) {
          this.bannerList = res.rows;
        }
      });
    },

    // 初始化申报列表  所有的申报列表
    initDeclareList() {
      // getDeclareList().then(res => {
      //   if (res.code == 200) {
      //     if (res.rows) {
      //       this.declareList = this.addDeclareDetail(res.rows);
      //     }
      //   }
      // });
      this.declareList = this.addDeclareDetail(this.declareTypeList);
    },
    addDeclareDetail(declareList) {
      let hasDetailList = [];
      declareList.forEach((item, index) => {
        // Object.assign(item,that.findDeclareRealItem(item.type))
        hasDetailList[index] = {
          ...item,
          ...this.findDeclareRealItem(item.type),
        };
        this.addCanDeclareList(hasDetailList[index]);
      });
      return hasDetailList;
    },
    addCanDeclareList(item) {
      let isCanDeclare = this.isOverNow(item.endTime);
      if (isCanDeclare) {
        this.canDeclareList.push(item);
      }
    },
    findDeclareRealItem(type) {
      if (this.declareTypeList) {
        let resItem = {};

        this.declareTypeList.forEach((item) => {
          if (type == parseInt(item.dictValue)) {
            resItem = item;
          }
        });

        return resItem;
      } else {
        return "";
      }
    },

    // 初始化明星企业
    inintStartList() {
      let requestObj = {
        pageSize: 5,
        pageNum: 1,
      };
      getEnterpriseList(requestObj).then((res) => {
        if (res.code == 200) {
          this.imgList = res.rows;
        }
      });
    },

    // 初始化 通知公告
    initNoticeList() {
      let requestObj = {
        pageSize: 5,
        pageNum: 1,
      };
      getNoticeList(requestObj).then((res) => {
        if (res.code == 200) {
          if (res.rows) {
            this.noticeList = res.rows.slice(0, 5);
          }
        }
      });
    },

    // 初始化 政策列表
    initPolicyList() {
      let requestObj = {
        pageSize: 5,
        pageNum: 1,
      };
      getPolicyList(requestObj).then((res) => {
        if (res.code == 200) {
          if (res.rows) {
            this.policyList = res.rows.slice(0, 5);
          }
        }
      });
    },

    noticeHeadSelect(index) {
      if (this.activeHeadIndex == index) {
        return;
      }
      this.activeHeadIndex = index;
    },
    handleBussSelect(key, path) {},

    toNoticeDetail(id) {
      this.$router.push({ name: "noticeDetail", query: { id: id } });
    },
    toPolicyDetail(id) {
      this.$router.push({ name: "policyDetail", query: { id: id } });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.register-container {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  background-color: #efefef;

  .bg-img {
    position: absolute;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;

    .el-image {
      width: 100%;
      height: 100%;
    }
  }

  .logo-container {
    z-index: 100;
    display: flex;
    align-items: center;
    height: 52px;
    width: 1200px;
    margin-bottom: 52px;
    font-size: 28px;

    .logo-img {
      height: 52px;
      width: 200px;

      .el-image {
        width: 100%;
        height: 100%;
      }
    }

    .sub-title {
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      text-align: left;
      color: #999999;
    }
  }

  @keyframes form-animation {
    0% {
      transform: translateY(30px);
    }

    25% {
      transform: translateY(22px);
    }

    50% {
      transform: translateY(15px);
    }

    75% {
      transform: translateY(8px);
    }

    100% {
      transform: translateY(0px);
    }
  }

  @keyframes form-opacity {
    from {
      opacity: 0;
    }

    to {
      opacity: 1;
    }
  }

  .form-container {
    position: relative;
    z-index: 100;
    display: flex;
    align-items: center;
    width: 1200px;
    height: 700px;
    border-radius: 10px;
    background-color: #fff;
    padding: 0;
    // box-shadow: 0 0 15px #979797;
    transform: translateY(0px);
    animation: form-animation 400ms ease;
    @apply shadow-lg;

    .float-left-img {
      height: 100%;
      width: 600px;
      @apply absolute left-0 top-0;

      .el-image {
        height: 100%;
      }
    }

    .form-box {
      height: 100%;
      width: 366px;
      margin-left: 731px;
      opacity: 0;
      animation: form-opacity 800ms ease 200ms;
      animation-fill-mode: forwards;

      // border: 1px solid #f0f;
      .form-title {
        font-size: 20px;
        font-family: Source Han Sans CN, Source Han Sans CN-Medium;
        margin: 123px 0 66px 0;

        .active {
          font-size: 24px;
          font-weight: 500;
          text-align: left;
          color: #1678ff;
        }
      }

      .el-form {
        width: 366px;

        ::v-deep.el-input {
          input[type="number"] {
            -moz-appearance: textfield;
          }

          input[type="number"]::-webkit-inner-spin-button,
          input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
          }

          .el-input__inner {
            height: 48px;
            line-height: 48px;
            border-radius: 4px;
            padding-left: 50px;
          }

          .el-input__prefix {
            padding: 0 10px;
          }
        }

        .login-icon {
          @apply flex items-center;
        }

        .code-input {
          ::v-deep .el-form-item__content {
            display: flex;

            justify-content: space-between;
            width: 100%;
          }

          ::v-deep .el-input {
            min-width: 60%;

            // width: 200px;
            // height: 48px;
            // line-height: 48px;
            // padding-right: 0;
            input[type="number"] {
              -moz-appearance: textfield;
            }

            input[type="number"]::-webkit-inner-spin-button,
            input[type="number"]::-webkit-outer-spin-button {
              -webkit-appearance: none;
              margin: 0;
            }

            .el-input__inner {
              border-radius: 4px 0 0 4px;
              // border-radius: 0;
              // border-width: 0 0 1px 0;
            }
          }

          .verify-btn-container {
            min-width: 40%;

            img {
              min-width: 100%;
            }

            .el-button {
              border-radius: 0 4px 4px 0;
              // border-radius: 10px;
            }
          }
        }

        .el-button {
          height: 48px;
          width: 100%;
          font-size: 18px;
          border-radius: 4px;
        }
      }
    }
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

::v-deep .el-input {
  display: flex;
  align-items: center;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-code-img {
  height: 38px;
}
</style>
